// 安装依赖
// npm install @pdf-lib/standard-fonts html2canvas docx-preview

import { PDFDocument, rgb, StandardFonts } from 'pdf-lib'
import { renderAsync } from 'docx-preview'
import html2canvas from 'html2canvas'

export function usePDFGenerator() {
    // PDF基础配置
    const pageWidth = 210 // A4 width in mm
    const pageHeight = 297 // A4 height in mm
    const margin = 10 // 页边距
    const dpi = 96 // 屏幕DPI

    const generatePDF = async (urls) => {
        // 创建主PDF文档
        const pdfDoc = await PDFDocument.create()
        const timesFont = await pdfDoc.embedFont(StandardFonts.Helvetica)

        // 当前页面状态
        let currentPage = pdfDoc.addPage([pageWidth, pageHeight])
        let currentY = pageHeight - margin // 从页面顶部开始

        for (const url of urls) {
            try {
                const type = getFileType(url)
                switch (type) {
                    case 'image':
                        await processImage(pdfDoc, url, currentPage, currentY)
                        break
                    case 'html':
                        await processHTML(pdfDoc, url, currentPage, currentY)
                        break
                    case 'docx':
                        await processDocx(pdfDoc, url, currentPage, currentY)
                        break
                    case 'pdf':
                        await mergePDF(pdfDoc, url)
                        break
                }
            } catch (error) {
                console.error(`处理文件 ${url} 失败:`, error)
                addErrorMessage(currentPage, `文件处理错误: ${url}`, currentY)
                currentY -= 15
            }
        }

        // 保存并打印
        const pdfBytes = await pdfDoc.save()
        const blob = new Blob([pdfBytes], { type: 'application/pdf' })
        printPDF(blob)
    }

    // 类型检测
    const getFileType = (url) => {
        if (/\.(png|jpe?g|webp)$/i.test(url)) return 'image'
        if (/\.html?$/i.test(url)) return 'html'
        if (/\.docx$/i.test(url)) return 'docx'
        if (/\.pdf$/i.test(url)) return 'pdf'
        return 'unknown'
    }

    // 处理图片内容
    const processImage = async (pdfDoc, url, currentPage, currentY) => {
        const imgBlob = await fetch(url).then(r => r.blob())
        const img = await pdfDoc.embedJpg(await imgBlob.arrayBuffer())

        // 计算缩放比例
        const maxWidth = pageWidth - margin * 2
        const scale = Math.min(maxWidth / img.width, 1)
        const imgHeight = img.height * scale

        // 分页检查
        if (currentY - imgHeight < margin) {
            currentPage = pdfDoc.addPage([pageWidth, pageHeight])
            currentY = pageHeight - margin
        }

        // 添加图片
        currentPage.drawImage(img, {
            x: margin,
            y: currentY - imgHeight,
            width: img.width * scale,
            height: imgHeight,
        })

        currentY -= imgHeight + margin
    }

    // 处理HTML内容
    const processHTML = async (pdfDoc, url, currentPage, currentY) => {
        const iframe = document.createElement('iframe')
        try {
            // 加载并渲染HTML
            await new Promise((resolve, reject) => {
                iframe.style.visibility = 'hidden'
                iframe.style.position = 'absolute'
                iframe.src = url
                document.body.appendChild(iframe)
                iframe.onload = resolve
                iframe.onerror = reject
            })

            // 转换为图片
            const canvas = await html2canvas(iframe.contentDocument.body, {
                scale: 0.5, // 控制分辨率
                useCORS: true,
            })

            // 处理图片分页
            const imgData = await pdfDoc.embedPng(canvas.toDataURL())
            const imgHeight = (canvas.height * 0.264) * 0.5 // 像素转毫米

            // 分页处理
            let remainingHeight = imgHeight
            while (remainingHeight > 0) {
                const availableHeight = currentY - margin
                const drawHeight = Math.min(availableHeight, remainingHeight)

                currentPage.drawImage(imgData, {
                    x: margin,
                    y: currentY - drawHeight,
                    width: pageWidth - margin * 2,
                    height: drawHeight,
                })

                remainingHeight -= drawHeight
                currentY -= drawHeight

                if (remainingHeight > 0) {
                    currentPage = pdfDoc.addPage([pageWidth, pageHeight])
                    currentY = pageHeight - margin
                }
            }
        } finally {
            document.body.removeChild(iframe)
        }
    }
    // 修改后的processDocx函数（带详细调试）
    const processDocx = async (pdfDoc, url) => {
        const container = document.createElement('div')
        try {
            console.log('[DEBUG] 开始处理DOCX文件:', url)

            // 容器样式
            container.style.cssText = `
        position: fixed;
        left: 0;
        top: -100%;
        width: 210mm;
        min-height: 297mm;
        background: white;
        z-index: 9999;
      `
            document.body.appendChild(container)
            console.log('[DEBUG] 容器已创建:', container)

            // 获取DOCX文件
            const response = await fetch(url)
            console.log('[DEBUG] 响应状态:', response.status, 'Content-Type:', response.headers.get('Content-Type'))

            const docxBlob = await response.blob()
            // console.log({ docxBlob }, await docxBlob.text())
            console.log('[DEBUG] DOCX Blob信息:', `大小: ${docxBlob.size} bytes, 类型: ${docxBlob.type}`)

            // 渲染DOCX
            console.log('[DEBUG] 开始渲染DOCX...')
            await renderAsync(docxBlob, container, null, {
                debug: true,
                ignoreFonts: false
            })
            console.log({ container })
            console.log("'container.innerHTML.substring(0, 200) + '...'", container.innerHTML.substring(0, 200) + '...')
            console.log('[DEBUG] DOCX渲染完成，容器内容:', container.innerHTML.substring(0, 200) + '...') // 打印部分HTML

            // 等待内容渲染
            await waitForRendering(container)

            // 转换为PDF
            console.log('[DEBUG] 开始转换PDF...')
            const pages = await convertDocxToPdf(container)
            console.log('[DEBUG] PDF转换完成，字节大小:', pages.byteLength)

            const extPdf = await PDFDocument.load(pages)
            const copiedPages = await pdfDoc.copyPages(extPdf, extPdf.getPageIndices())
            copiedPages.forEach(page => pdfDoc.addPage(page))
            console.log('[DEBUG] 已添加', copiedPages.length, '个页面')
        } catch (e) {
            console.error('[ERROR] DOCX处理异常:', e)
            throw e
        } finally {
            document.body.removeChild(container)
            console.log('[DEBUG] 已清理容器')
        }
    }

    // 增强版convertDocxToPdf（带调试和临时文件保存）
    async function convertDocxToPdf(container) {
        console.log('convertDocxToPdf', { container })
        const pdfDoc = await PDFDocument.create()

        // 获取所有页面块
        const pageBlocks = Array.from(container.querySelectorAll('.docx'))
        console.log("container.querySelectorAll('.docx-section')", container.querySelectorAll('.docx-section'))
        console.log('[DEBUG] 发现DOCX分页区块:', pageBlocks.length)

        for (const [index, section] of pageBlocks.entries()) {
            const originalDisplay = section.style.display
            try {
                console.log(`[DEBUG] 正在处理第${index + 1}页...`)

                // 临时显示元素
                section.style.display = 'block'

                // 创建canvas
                const canvas = await html2canvas(section, {
                    scale: 1.5,
                    useCORS: true,
                    logging: true,
                    onclone: (clonedDoc, element) => {
                        console.log('[DEBUG] 克隆元素:', element)
                        element.style.visibility = 'visible'
                    }
                })

                // 保存调试图片
                const debugImg = document.createElement('img')
                debugImg.src = canvas.toDataURL()
                debugImg.style.position = 'fixed'
                debugImg.style.top = '0'
                debugImg.style.right = '0'
                debugImg.style.width = '300px'
                debugImg.style.zIndex = '99999'
                document.body.appendChild(debugImg)
                console.log('[DEBUG] Canvas信息:',
                    `尺寸: ${canvas.width}x${canvas.height}, 数据类型: ${typeof canvas.toDataURL().substring(0, 50)}...`)

                // 转换尺寸
                const mmPerInch = 25.4
                const width = canvas.width / 96 * mmPerInch
                const height = canvas.height / 96 * mmPerInch
                console.log('[DEBUG] 转换后的PDF页面尺寸:', `${width.toFixed(1)}mm x ${height.toFixed(1)}mm`)

                // 嵌入PDF
                const img = await pdfDoc.embedPng(canvas.toDataURL())
                const page = pdfDoc.addPage([width, height])
                page.drawImage(img, { x: 0, y: 0, width, height })

                // 清理调试元素
                setTimeout(() => document.body.removeChild(debugImg), 3000)
            } finally {
                section.style.display = originalDisplay
            }
        }

        return pdfDoc.save()
    }

    // 辅助函数：带超时的渲染等待
    async function waitForRendering(container, timeout = 10000) {
        console.log('waitForRendering', { container })
        console.log('[DEBUG] 开始等待渲染...')
        const start = Date.now()

        while (Date.now() - start < timeout) {
            const visibleElements = container.querySelectorAll('p, table, img')
            console.log(`[DEBUG] 可见元素数量: ${visibleElements.length}`, { visibleElements })

            if (visibleElements.length > 0) {
                console.log('[DEBUG] 检测到有效内容，继续处理')
                return true
            }

            await new Promise(r => setTimeout(r, 500))
        }

        throw new Error('等待渲染超时')
    }

    // 合并外部PDF
    const mergePDF = async (pdfDoc, url) => {
        const extBytes = await fetch(url).then(r => r.arrayBuffer())
        const extPdf = await PDFDocument.load(extBytes)
        const copiedPages = await pdfDoc.copyPages(extPdf, extPdf.getPageIndices())
        copiedPages.forEach(page => pdfDoc.addPage(page))
    }

    // 错误信息添加
    const addErrorMessage = (page, text, y) => {
        page.drawText(text, {
            x: margin,
            y,
            size: 8,
            color: rgb(1, 0, 0),
        })
    }

    // 打印处理
    const printPDF = (blob) => {
        const url = URL.createObjectURL(blob)
        const iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = url
        document.body.appendChild(iframe)
        iframe.onload = () => {
            iframe.contentWindow?.print()
            setTimeout(() => URL.revokeObjectURL(url), 10000)
        }
    }

    return { generatePDF }
}
